import 'package:flutter/material.dart';
import 'package:visibility_detector/visibility_detector.dart';

enum VisibilityLevel{
  ///完全可见
  full,
  ///部分可见
  part,
}


///组件是否可见
class VisibilityWidget extends StatefulWidget {

  final Widget child;

  /// visibleValue可见程度 0~1， 1完全展示
  final void Function(double visibleValue)? visibleValueCallback;

  /// show, true可见，false不可见
  final void Function(bool show)? visibleShowCallback;

  ///设置进行回调通知的可见程度
  final VisibilityLevel visibilityLevel;

  VisibilityWidget({
    Key? key,
    required this.child,
    this.visibleValueCallback,
    this.visibleShowCallback,
    this.visibilityLevel = VisibilityLevel.full,
  }) : super(key: key);

  @override
  _VisibilityWidgetState createState() {
    return _VisibilityWidgetState();
  }
}

class _VisibilityWidgetState extends State<VisibilityWidget> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  bool _show = false;
  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: widget.key ?? Key("$hashCode"),
      onVisibilityChanged: (info) {
        // debugPrint("onVisibilityChanged ${info.visibleFraction}");
        widget.visibleValueCallback?.call(
          info.visibleFraction,
        );
        if (widget.visibilityLevel == VisibilityLevel.full) {
          if (info.visibleFraction == 1 || info.visibleFraction == 0) {
            widget.visibleShowCallback?.call(
              info.visibleFraction == 1,
            );
          }
        } else if (widget.visibilityLevel == VisibilityLevel.part) {
          if (info.visibleFraction > 0) {
            if (_show == false) {
              _show = true;
              widget.visibleShowCallback?.call(true);
            }
          } else {
            _show = false;
            widget.visibleShowCallback?.call(false);
          }
        }
      },
      child: widget.child,
    );
  }
}
